package com.lu.servlet;

import com.lu.pojo.User;
import com.lu.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

@WebServlet(name = "LoginServlet", urlPatterns = {"/Login"})
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");

        PrintWriter out = resp.getWriter();

        String uname = req.getParameter("uname");
        String upassword = req.getParameter("upassword");
        User user = new UserServiceImpl().getOneUser(uname, upassword);
        if (user != null) {
            // 存入会话
            req.getSession().setAttribute("currentUser", user);
            List<User> currentUserList = (List<User>) req.getServletContext().getAttribute("currentUserList");
            if (currentUserList == null) {
                currentUserList = new ArrayList<>();
            }
            if (!currentUserList.contains(user)) {
                currentUserList.add(user);
            }
            req.getServletContext().setAttribute("currentUserList", currentUserList);
            if (user.getUtype() == 0) {
                resp.sendRedirect("admin_0.jsp");
            } else if (user.getUtype() == 1) {
                resp.sendRedirect("admin_1.jsp");
            }
        } else {
            resp.sendRedirect("index.jsp");
        }

        out.flush();
        out.close();
    }
}
